CONTENTS | INDEX | PREV | NEXT
freopen
NAME
freopen - reopen a new file using an existing file pointer,
the existing file is closed before it is reused.
SYNOPSIS
#include <stdio.h>
FILE *fp = freopen(filename, modes, ofp)
char *filename;
char *modes;
FILE *ofp;
FUNCTION
freopen works exactly like fopen but takes an additional argument...
A file pointer to reuse. This file pointer, ofp, must be reference
a valid open file. freopen() will close out ofp then reuse the
descriptor to open the new file, returning ofp (fp == ofp) on
success, NULL on failure.
If the freopen fails NULL is returned and the original file
pointer is still closed, but not free()d so you may call
freopen again with the same ofp, even though it has already
been closed.
refer to the fopen() manual page for information on the modes
string.
freopen is often used to change a program's stdin, stdout, or
stderr though to be frank, using a separate file pointer is
normally much more modular.
WARNING
ANSI does not specify that the ofp can be used in a second freopen
if the first freopen using ofp fails (returns NULL). Many
implementations free the file pointer. This just might be
the proper way of doing things but I dunno. I suggest you do
not use DICE's feature in that respect as I might have to
change it back to free ofp if the new file is unopenable.
NOTE
refer to the file_pointer manual page for general information
EXAMPLE
/*
* re-open stdin to an Amiga console device
*/
#include <stdio.h>
#include <assert.h>
main()
{
char buf[256];
assert(freopen("CON:0/0/320/100/freopen-in", "r", stdin));
assert(freopen("CON:320/0/320/100/freopen-out", "w", stdout));
/*
* set to line buffered
*/
setvbuf(stdin, NULL, _IOLBF, 0);
setvbuf(stdout, NULL, _IOLBF, 0);
puts("Type a line in the second window");
gets(buf);
fclose(stdin);
fclose(stdout);
fprintf(stderr, "Your line was: %sn", buf);
return(0);
}
INPUTS
char *filename; file name to open
char *modes; open modes string
FILE *ofp; open file pointer to reuse
RESULTS
FILE *fp; same as ofp if the new open worked, NULL otherwise
SEE ALSO
fdopen, fopen, fclose, open, close